package io.renren.modules.vastFinance.controller;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import io.renren.common.utils.Result;
import io.renren.modules.vastFinance.dao.RepaymentDao;
import io.renren.modules.vastFinance.entity.RepaymentEntity;
import io.renren.modules.vastFinance.enums.EnumType;
import io.renren.modules.vastFinance.enums.Numeric;
import io.renren.modules.vastFinance.service.RepaymentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.vastFinance.entity.BorrowerEntity;
import io.renren.modules.vastFinance.service.BorrowerService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2022-05-20 08:55:54
 */
@RestController
@RequestMapping("vastFinance/borrower")
public class BorrowerController {
    @Autowired
    private BorrowerService borrowerService;
    @Autowired
    private RepaymentDao repaymentDao;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("vastFinance:borrower:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = borrowerService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{borrowId}")
    @RequiresPermissions("vastFinance:borrower:info")
    public R info(@PathVariable("borrowId") Integer borrowId){
		BorrowerEntity borrower = borrowerService.getById(borrowId);

        return R.ok().put("borrower", borrower);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("vastFinance:borrower:save")
    public R save(@RequestBody BorrowerEntity borrower){
		borrowerService.save(borrower);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("vastFinance:borrower:update")
    public R update(@RequestBody BorrowerEntity borrower){
		borrowerService.updateById(borrower);
		//判断是否审批成功
		if(borrower.getStates()==1){
            //添加贷款信息同时生成还款计划表信息
            //1.判断贷款规则
//            String str =  borrower.getLoanperiods().substring(0, 1);
//            Integer num = Integer.valueOf(str);
            String str =  borrower.getLoanperiods();
            String numeric = Numeric.getNumeric(str);
            int num = Integer.parseInt(numeric);
            if(EnumType.ONE.getEnuTypeName().equals( borrower.getRepaymentType())){
                //等额本息
                double invest = borrower.getPrice();     //贷款本金
                double yearRate =borrower.getAnnual()/100;   //年利率
                double monthRate = yearRate / 12;   //月利率

//
                int month = num;  //还款月数

                // 每月本金 = 本金×月利率×(1+月利率)^(还款月序号-1)÷((1+月利率)^还款月数-1))
                double monthCapital = 0;
                // 每月利息  = 剩余本金 x 贷款月利率
                double monthInterest = 0;
                double capital = invest;
                double tmpCapital = 0;
                double totalInterest = 0;
                Date time=null;
                for (int i = 1; i < month + 1; i++) {
                    RepaymentEntity repaymentEntity = new RepaymentEntity();
                   //添加时间
                    if(i==1){
                        time=borrower.getStartTime();
                        repaymentEntity.setRepayTime(time);
                    }
                    monthCapital = (invest * monthRate * (Math.pow((1 + monthRate), i - 1))) / (Math.pow(1 + monthRate, month) - 1);
                    capital = capital - tmpCapital;
                    monthInterest = capital * monthRate;
                    tmpCapital = (invest * monthRate * (Math.pow((1 + monthRate), i - 1))) / (Math.pow(1 + monthRate, month) - 1);
                    System.out.println("第" + i + "月利息： " + monthInterest);
                    totalInterest = totalInterest + monthInterest;
                    System.out.println("第" + i + "月本金： " + monthCapital);
                    //添加
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(time);
                    rightNow.add(Calendar.MONTH,1);
                    time = rightNow.getTime();
                    repaymentEntity.setRepayTime(time);
                    //本金
                    repaymentEntity.setCapital(monthCapital);
                    //利息
                    repaymentEntity.setAccrual(monthInterest);
                    repaymentEntity.setBorrowId(borrower.getBorrowId());
                    repaymentEntity.setPeriods(i);
                    repaymentDao.insert(repaymentEntity);
                }
            }



            if(EnumType.TWO.getEnuTypeName().equals( borrower.getRepaymentType())){
                //等额本金
            }
            if(EnumType.THREE.getEnuTypeName().equals(borrower.getRepaymentType())){
                //每月还息一次还本
                //计算每月利息
                Double price= borrower.getPrice()*(borrower.getAnnual()/100/12);
                Date time=null;
                for (int i=1;i<=num;i++){
                    RepaymentEntity repaymentEntity = new RepaymentEntity();
                    if(i==1){
//                        Date NowTime= borrower.getStartTime();
//                        Calendar rightNow = Calendar.getInstance();
//                        rightNow.setTime(NowTime);
//                        rightNow.add(Calendar.MONTH,1);
//                        time = rightNow.getTime();
                        time=borrower.getStartTime();
                        repaymentEntity.setRepayTime(time);
                    }
                    if(i<=num-1){
                        repaymentEntity.setCapital(0.0);
                    }
                    if(i==num){
                        repaymentEntity.setCapital(Double.valueOf(borrower.getPrice()));
                    }
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(time);
                    rightNow.add(Calendar.MONTH,1);
                    time = rightNow.getTime();
                    repaymentEntity.setRepayTime(time);
                    repaymentEntity.setAccrual(price);
                    repaymentEntity.setBorrowId(borrower.getBorrowId());
                    repaymentEntity.setPeriods(i);
                    repaymentDao.insert(repaymentEntity);
                }
            }

            if(EnumType.FOUR.getEnuTypeName().equals(borrower.getRepaymentType())){
                //一次还本还息
            }
        }

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("vastFinance:borrower:delete")
    public R delete(@RequestBody Integer[] borrowIds){
		borrowerService.removeByIds(Arrays.asList(borrowIds));

        return R.ok();
    }


    /**
     * 获取每月本息金额
     * 计算方式
     * 每月本息金额  = (本金×月利率×(1＋月利率)＾还款月数)÷ ((1＋月利率)＾还款月数-1))
     * @param invest  本金
     * @param yearRate 年利率
     * @param month   还款月
     * @return 每月本息金额
     */
    public double getMonthIncome ( double invest, double yearRate, int month){
        double monthRate = yearRate / 12;   //月利率
        double monthIncome = (invest * monthRate * Math.pow(1 + monthRate, month)) / (Math.pow(1 + monthRate, month) - 1);
        return monthIncome;
    }

    /**
     * 审核更改状态
     * @param borrowId
     * @param infoStatus
     */
    @RequestMapping("examination")
    public void examination(@RequestParam("borrowId") Integer borrowId,@RequestParam("infoStatus") Integer infoStatus){
        borrowerService.examination(borrowId,infoStatus);
    }

    /**
     * 计算利息
     * @param borrowerEntity
     * @return
     */
    @RequestMapping("computer")
    public Result computer(@RequestBody BorrowerEntity borrowerEntity){
        return borrowerService.computer(borrowerEntity);
    }

}
